package com.gopay.checkorder.service.task;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.Result;
import com.gopay.common.domain.bank.wechat.scan.cmbc.FetchCheckAccntFile;
import com.gopay.common.domain.bank.wechat.scan.cmbc.FileDownReq;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.SendMail;
import com.gopay.remote.bank.ScanPayMerchantService;

/**
 * 民生扫码支付下载对账文件
 *
 * @author jiangxiangjiao
 * @date 2016-10-19
 */
public class CmbcScanDownloadTaskImpl implements Task {
	private final static Logger logger = LoggerFactory.getLogger("CHECK_ORDER");

	@Resource(name = "cmbcScanDownCheckAcctFileConfig")
	private Map<String, String> cmbcScanDownCheckAcctFileConfig;

	@Resource(name = "downCheckAcctFileClient")
	private ScanPayMerchantService cmbcDownCheckAcctFileClient;

	@Override
	public void doTask() {
		// 对账单文件名格式：cmbc-scanPay-20161020.txt
		// 对账单文件夹：/usr/local/ciecc/bankFiles/CMBC_SCAN/
		// 1.检查文件夹里是否已有昨天对账单文件
		// 2.如果没有则接口查对账单
		// 3.将对账单形成文件放在文件夹里
		// 4.作为附件发送邮件
		logger.error("CmbcScanDownloadTaskImpl: 定时任务start ");
		try {
			/**************** 为了测试，注释该部分 ************************/

			if ("off".equals(cmbcScanDownCheckAcctFileConfig.get("mailSwitch"))) {
				logger.error("CmbcScanDownloadTaskImpl: 不进行操作直接返回!");
				return;
			}

			// 生成对账单文件所需参数
			String locpath = cmbcScanDownCheckAcctFileConfig.get("locpath");

			String fTime = DateUtils.getYesterday();
			/**************** 为了测试，固定对账日期(有交易) ************************/
			//String fTime = "20171020";

			String fName = "cmbc-scanPay-" + fTime + ".txt";
			List<String> sendFile = new ArrayList<String>();
			List<String> names = new ArrayList<String>();
			String messageText = "";

			File dir = new File(locpath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			if (!(new File(locpath + fName).exists())) {
				String content = getCheckAccountFile(fTime);
				String alipayContent = getCheckAccountAlipayFile(fTime);
				String fileContent=content+"\r\n"+alipayContent;
				
				boolean flag = string2File(fileContent, locpath + fName);
				if (flag) {
					names.add(fName);
					logger.error("CmbcScanDownloadTaskImpl " + fName + " 对账文件生成成功!");
				} else {
					logger.error("CmbcScanDownloadTaskImpl " + fName + " 对账文件生成失败!");
					return;
				}
			} else {
				logger.error("CmbcScanDownloadTaskImpl " + fName + " 对账文件已存在!");
			}

			// 若对账文件全部为空，则邮件内容标明
			if (names.size() < 1) {
				logger.error("CmbcScanDownloadTaskImpl: 民生扫码对账文件为null或本地已成功下载!");
				return;
			} else {
				messageText = fTime + ": 民生扫码对账文件见附件!" + fName;
				for (int i = 0; i < names.size(); i++) {
					sendFile.add(locpath + names.get(i));
				}
			}
			String subject = "民生扫码对账文件";
			String[] cc = cmbcScanDownCheckAcctFileConfig.get("sendmail.cc").split(","); // 获取多个抄送人
			List<String> ccList = Arrays.asList(cc);

			logger.error("sendMessage  config:--host:" + cmbcScanDownCheckAcctFileConfig.get("sendmail.host")
					+ "----sender:" + cmbcScanDownCheckAcctFileConfig.get("sendmail.sender") + "----username:"
					+ cmbcScanDownCheckAcctFileConfig.get("sendmail.username") + "----password:"
					+ cmbcScanDownCheckAcctFileConfig.get("sendmail.password") + "----receiver:"
					+ cmbcScanDownCheckAcctFileConfig.get("sendmail.receiver"));
			// 发送邮件
			SendMail.sendMessage(cmbcScanDownCheckAcctFileConfig.get("sendmail.host"),
					cmbcScanDownCheckAcctFileConfig.get("sendmail.sender"),
					cmbcScanDownCheckAcctFileConfig.get("sendmail.username"),
					cmbcScanDownCheckAcctFileConfig.get("sendmail.password"),
					cmbcScanDownCheckAcctFileConfig.get("sendmail.receiver"), subject, messageText,
					"text/html;charset=gb2312", ccList, sendFile, names);
			logger.error("------民生扫码发送邮件成功--------");

		} catch (Exception e) {
			logger.error("CmbcScanDownloadTaskImpl error: ", e);
		}
	}

	/**
	 * 接口查对账单
	 *
	 * @return
	 * @throws GopayException
	 */
	private String getCheckAccountFile(String date) throws GopayException {
		FileDownReq fileDownReq=new FileDownReq();
		fileDownReq.setDate(date);
		fileDownReq.setFileType("1");
		fileDownReq.setChannel("17");
		Result result = cmbcDownCheckAcctFileClient.getCheckAccountFile(fileDownReq);
		FetchCheckAccntFile message = (FetchCheckAccntFile) result.getDefaultModel();
		String content = message.getContent();
		// 报文返回成功且对账内容不全为#，则返回对账内容
		if (result.isSuccess()) {
			return message.getContent();
		}
		return content;
	}
	private String getCheckAccountAlipayFile(String date) throws GopayException {
		FileDownReq fileDownReq=new FileDownReq();
		fileDownReq.setDate(date);
		fileDownReq.setFileType("1");
		fileDownReq.setChannel("17");
		Result result = cmbcDownCheckAcctFileClient.getCheckAlipayAccountFile(fileDownReq);
		FetchCheckAccntFile message = (FetchCheckAccntFile) result.getDefaultModel();
		String content = message.getContent();
		// 报文返回成功且对账内容不全为#，则返回对账内容
		if (result.isSuccess()) {
			return message.getContent();
		}
		return content;
	}

	/**
	 * 生成数据文件
	 *
	 * @param filePath
	 *            写入文件的路径
	 * @param content
	 *            写入的字符串内容
	 * @return
	 */
	public boolean string2File(String content, String filePath) {
		BufferedReader bufferedReader = null;
		BufferedWriter bufferedWriter;
		boolean flag = true;
		try {
			File file = new File(filePath);
			if (!file.exists()) {
				file.createNewFile();
			}
			bufferedReader = new BufferedReader(new StringReader(content));
			bufferedWriter = new BufferedWriter(new FileWriter(file));
			char buffer[] = new char[1024];
			int len;
			while ((len = bufferedReader.read(buffer)) != -1) {
				bufferedWriter.write(buffer, 0, len);
			}
			bufferedWriter.flush();
			bufferedReader.close();
			bufferedWriter.close();
		} catch (IOException e) {
			logger.error(String.valueOf(e));
			flag = false;
			return flag;
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					logger.error(String.valueOf(e));
				}
			}
		}
		return flag;
	}

}
